var q = require('q');

function ifThrow() {
    return Math.random() > 0.55;
}

function foo() {
    var defer = q.defer();
    process.nextTick(function() {
        if (ifThrow()) defer.reject('rrr');
        else defer.resolve('fff');
    })
    return defer.promise;
}


var status = 'before foo';
foo()

// then 
.then(function f(arg) {
    console.log('now then1, arg=%s', arg);
    if (ifThrow()) throw new Error('error hello111');
    else return 'then1 done';
})

// then
.then(function f(arg) {
    console.log('now then2, arg=%s', arg);
    if (ifThrow()) throw new Error('error hello222');
    else return 'then2 done';
})

// fail not Promise standard, only for q, same to catch
// .fail(function(arg) {
//     console.log('on fail, error=', arg);
// })

.catch(function(arg) {
    console.log('on catch, error=', arg);
    return 'catch done';
})

// can do then after catch
.then(function f(arg) {
    console.log('after catch/fail, then arg=%s', arg);
    return 'then3 done';
})

// finally not Promise standard, only for q
.finally(function(arg) { // arg always undefind
    status = 'foo finished';
    console.log('finally arg=%s', arg);
})

.done();


process.on('exit', function() {
    console.log('on exit, status =%s', status);
})